<?php
namespace app\common\model;


use think\Model;

abstract class BaseModel extends Model
{
    // 声明对象是否需要数据隔离
    public static $searchCommon = false;


    // 申明数据隔离字段
    public static $commonFields = ['merchant_id','create_merchant_id'];
    /**
     * 自动时间戳类型
     * @var string
     */
    protected $autoWriteTimestamp = true;

    /**
     * 添加时间
     * @var string
     */
    protected $createTime = 'created_at';

    /**
     * 更新时间
     * @var string
     */
    protected $updateTime = 'updated_at';


    /**
     * @return string
     */
    abstract public static function tablePk():? string;

    /**
     * @return string
     */
    abstract public static function tableName(): string;

    /**
     * BaseModel constructor
     * @param array $data
     */
    public function __construct(array $data = [])
    {
        $this->pk = static::tablePk();
        $this->name = static::tableName();
        parent::__construct($data);
    }

    /**
     * @return static
     */
    public static function getInstance(): self
    {
        return new static();
    }

    public static function common($bool = false){
        static::$searchCommon = $bool;
    }

    /**
     * @param array $scope
     * @param bool $searhCommon
     * @param string $prefix  表标识
     * @return BaseQuery
     * @author xaboy
     * @day 2020-03-30
     */
    public static function getDB(array $scope = [],bool $searhCommon = true, string $prefix = '')
    {

        if(!$searhCommon) {
            self::$searchCommon = false;
        }
        $commonWhere = [];
        // 如果本类开启了数据隔离且 数据表有公共数据隔离字段  且环境池不为空则查询时添加公共查询条件
        if(static::$searchCommon && self::checkCommonFields()) {
            $commonWhere = self::getCommonSearchWhere($prefix);
        }
        if(!empty($commonWhere)){
            return self::getInstance()->db($scope)->where($commonWhere);
        }else{
            return self::getInstance()->db($scope);
        }
    }

    /**
     * @desc 获取公共查询结果
     * @param string $prefix
     * @return array $where
     * @author xiaohp
     */
    public static function getCommonSearchWhere(string $prefix = ''): array {
        $where = [];
        if(!empty(self::$commonFields)){
            $tableFields = self::getFields();
            //不能使用缓存 缓存会常驻内存
            $commonCache = [];
            if(!empty($commonCache)){
                foreach(self::$commonFields as $field){
                    if(isset($tableFields[$field]) && $tableFields[$field]['name'] == $field){
                        $val = $commonCache[$field] ?? '';
                        if($val != null && $val !== '' && $val > 0){
                            if($prefix)
                            {
                                $where[$prefix.'.'.$field] = $val;
                            }
                            else
                            {
                                $where[$field] = $val;
                            }
                        }
                    }
                }
            }
        }
        return $where;
    }

    /**
     * @desc 检查是否有公共字段
     * @author xiaohp
     * @return bool $exists
     */
    public static function checkCommonFields(): bool {
        $exists = false;
        if(!empty(self::$commonFields)){
            $tableFields = static::getFields();
            foreach(self::$commonFields as $field){
                if(isset($tableFields[$field]) && $tableFields[$field]['name'] == $field){
                    $exists = true;
                    break;
                }
            }
        }
        return $exists;
    }
    /**
     * @desc 插入前插入公共保存字段
     * @author xiaohp
     * @return array $where
     */
    public static function onBeforeWrite($model){
        $check = self::checkCommonFields();
        $commonFields = self::getCommonSearchWhere();
        $exists = $model->offsetGet('exists');
        if($check && !empty($commonFields) && !$exists){
            foreach($commonFields as $field => $val){
                if ($val > 0) {
                    if($model->offsetGet($field) === '' || $model->offsetGet($field) === null){
                        $model->offsetSet($field,$val);
                    }
                }
            }
        }
    }

    /**
     * @desc: 重写插入后事件 站位 否则 parent 语法会报错
     * @author: xiaohp
     * @param {*} $model
     */
    public static function onAfterInsert($model){

    }

    /**
     * @desc: 重写更新后事件  站位 否则 parent 语法会报错
     * @author: xiaohp
     * @param {*} $model
     */    
    public static function onAfterUpdate($model){
    }
}